// 请求配置
import Config from "@/config/config.js"
module.exports = (vm) => {
	uni.$u.http.setConfig((config) => {
		config.baseURL = Config.websiteUrl;
		config.timeout = 15000;
		config.dataType = 'json',
			config.header = {
				'Content-Type': 'application/json',
				"Access-Control-Allow-Origin": "*",
				"Access-Control-Allow-Method": "POST,GET,UPLOAD,DELETE",
			};
		return config
	})

	uni.$u.http.interceptors.request.use((config) => {
		// 是否加token
		if (config?.custom?.auth) {
			config.header.authorization = uni.getStorageSync('accessToken')
		}
		// 是否显示loading
		if (config?.custom?.loading) {
			uni.showLoading({
				title: '加载中',
				mask: true
			})
		}
		return config
	}, config => {
		return Promise.reject(config)
	})

	uni.$u.http.interceptors.response.use((response) => {
		if (response.config.custom.loading) {
			uni.hideLoading()
		}
		switch (response.data.code) {
			case 401:
				uni.$u.route({
					type: 'reLaunch',
					url: 'pages/login/login'
				});
				break;
			case 200:
				return response.data || response.rows
				break;
			default:
				uni.$u.toast(response.data.msg)
				return response.data
				break;
		}
	}, (response) => {
		if (response.config.custom.loading) {
			uni.hideLoading()
		}
		uni.$u.toast('请求失败,请稍后再试！')
		uni.$emit('z-paging-error-emit')
		return Promise.reject(response)
	})
}
